package com.ruoyi.web.course;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.course.domain.SExam;
import com.ruoyi.course.domain.SExamQuestion;
import com.ruoyi.course.vo.SExamQuestionVo;
import com.ruoyi.course.vo.SExamVo;
import com.ruoyi.course.service.ISExamService;
import com.ruoyi.course.vo.SaveAnswerVO;
import com.ruoyi.teacher.domain.TExam;
import com.ruoyi.teacher.domain.TOption;
import com.ruoyi.teacher.domain.TPaperQuestion;
import com.ruoyi.teacher.domain.TQuestion;
import com.ruoyi.teacher.service.ITQuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 学生考试Controller
 *
 * @author ruoyi
 * @date 2024-12-03
 */
@Api(tags = "学生考试Controller")
@RestController
@RequestMapping("/course/s_exam")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SExamController extends BaseController {

    private final ISExamService sExamService;
    @Autowired
    private ITQuestionService questionService;


    @ApiOperation("查询学生考试列表")
    @PreAuthorize("@ss.hasPermi('course:s_exam:list')")
    @GetMapping("/list")
    public TableDataInfo<SExamVo> list(SExamVo entity) {
        return sExamService.queryList(entity);
    }

    @ApiOperation("查询学生考试所有列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(SExamVo entity) {
        return AjaxResult.success("查询成功", sExamService.queryAll(entity));
    }




    @ApiOperation("导出学生考试列表")
    @PreAuthorize("@ss.hasPermi('course:s_exam:export')")
    @Log(title = "学生考试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SExamVo entity) {
        List<SExamVo> list = sExamService.queryAll(entity);
        ExcelUtil<SExamVo> util = new ExcelUtil<>(SExamVo.class);
        util.exportExcel(response, list, "学生考试数据");
    }

    @ApiOperation("获取学生考试详细信息")
    @PreAuthorize("@ss.hasPermi('course:s_exam:query')")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success("查询成功", sExamService.queryById(id));
    }

    @ApiOperation("新增学生考试")
    @PreAuthorize("@ss.hasPermi('course:s_exam:add')")
    @Log(title = "学生考试", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody SExamVo entity) {
        return toAjax(sExamService.save(entity));
    }

    @ApiOperation("修改学生考试")
    @PreAuthorize("@ss.hasPermi('course:s_exam:edit')")
    @Log(title = "学生考试", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody SExamVo entity) {
        return toAjax(sExamService.updateById(entity));
    }

    @ApiOperation("删除学生考试")
    @PreAuthorize("@ss.hasPermi('course:s_exam:remove')")
    @Log(title = "学生考试", businessType = BusinessType.DELETE)
	@GetMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sExamService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 获取考试信息（包括考试信息和答题信息）
     * @param studentExamId
     * @return
     */
    @GetMapping("/getExamInfo")
    public  AjaxResult getExamInfo(Integer studentExamId){
//    根据eid获得exam
        TExam exam = sExamService.getExam(studentExamId);
//         根据studentExamId得到studentQuestionList
        List<SExamQuestion> studentQuestionList = sExamService.getStudentQuestionList(studentExamId);
        // studentQuestionList 转成 StudentQuestionVOListList
        List<List<SExamQuestionVo>> lists = sExamService.getStudentQuestionVOListList(studentQuestionList);

                // 得到studentExam
        SExam studentExam = sExamService.getById(studentExamId);
        // 得到开始时间
        Date startTime = studentExam.getStartTime();
        // 得到当前时间
        Date curTime = new Date();
        // 已经过了的时间
        long passSeconds = (curTime.getTime() - startTime.getTime()) / 1000;
        // 计算剩余时间
        long leftSeconds = exam.getDuration() * 60 - passSeconds;
        // 整合
        Map<String, Object> res = new HashMap<>();
        res.put("examInfo", exam);
        res.put("questionList", lists);
        res.put("leftSeconds", leftSeconds);

        return AjaxResult.success(res);
    }
    /**
     * 根据paperId和questionId获取问题
     * @param questionId
     * @return
     */
    @GetMapping("/getQuestion")
    public AjaxResult getQuestion(Integer paperId, Integer questionId) {
        // 获取question
        TQuestion question = questionService.getById(questionId);

        // 获取paperQuestion
        TPaperQuestion paperQuestion = sExamService.getPaperQuestion(paperId, questionId);
        // 根据questionId查询选项
        List<TOption> options = sExamService.getOptions(question.getId());

        // 整合VO
        SExamQuestionVo sExamQuestionVo = new SExamQuestionVo();
        BeanUtils.copyProperties(question, sExamQuestionVo);
        BeanUtils.copyProperties(paperQuestion, sExamQuestionVo);
        sExamQuestionVo.setOptions(options);
        // 返回结果
        return AjaxResult.success(sExamQuestionVo);
    }
    /**
     * 保存回答
     * @param saveAnswerDTO
     * @return
     */
    @PostMapping("/saveAnswer")
    public AjaxResult saveAnswer(@RequestBody SaveAnswerVO saveAnswerDTO) {
        // 更新回答
        sExamService.updateAnswer(saveAnswerDTO);

        // 返回结果
        return AjaxResult.success("保存成功");
    }
}
